<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/4/22
 * Time: 10:38
 */

namespace app\admin\controller;

use app\model\AdminModel;
use think\facade\Request;
use think\facade\Validate;
use think\facade\View;

class Login
{
    public function index()
    {
        return View::fetch();
    }

    public function login()
    {
        $params = Request::param();
        $validate = Validate::rule([
            'admin_email|管理员邮箱' => 'require|min:1|max:100',
            'admin_password|密码' => 'require|min:6|max:20',
            'verify_code|验证码' => 'require|min:4|max:4',
        ]);
        if (!$validate->check($params)) {
            echo $validate->getError();
            exit();
        }
        session_start();
        if ($_SESSION['verify_code'] != $params['verify_code']) {
            return View::fetch('public/tips_error', ['message' => '验证码不对']);
        }

        $admin = AdminModel::where("admin_email", '=', $params['admin_email'])->find();
        $result = false;
        if ($admin && AdminModel::checkPassword($params['admin_password'], $admin['admin_password'])) {
            session("admin_email", $admin['admin_email']);
            session("admin_name", $admin['admin_name']);
            $result = true;
        }

        return View::fetch('', ['result' => $result]);
    }

    public function logout()
    {
        session("admin_name", null);
        session("admin_email", null);

        return View::fetch('');
    }

    public function verifyCode()
    {
        session_start();

        $image = \imagecreate(58, 25); // 创建一张图片
        $white = \imagecolorallocate($image, 255, 255, 255);// 创建背景为白色

        $verifyCode = '';
        for ($i = 1; $i <= 4; $i++) {
            $str = mt_rand(0, 9); // 要插入的字符串
            $font = 4; // 字体大小，如果 font 是 1，2，3，4 或 5，则使用内置字体。
            $x = 2 + ($i - 1) * 15; // 左偏移量，每画1个，左偏移量就加大一些。
            $y = 5; // 上偏移量
            $color = \imagecolorallocate($image, 255, 192, 203); // 设置一个浅粉色
            \imagestring($image, $font, $x, $y, $str, $color); // 将字符串画到图片上

            $verifyCode .= $str;
        }
        $_SESSION['verify_code'] = $verifyCode;

        header("Content-type: image/png");
        \imagepng($image); // 以 PNG 格式将图像输出到浏览器
        \imagedestroy($image); // 销毁一图像， 释放资源
    }
}